package com.scsj.supermarket.view.fragment.marketmodel;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.graphics.PointF;
import android.os.Bundle;
import android.support.design.widget.BottomSheetDialogFragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.gigamole.navigationtabstrip.NavigationTabStrip;
import com.orhanobut.logger.Logger;
import com.scsj.supermarket.R;
import com.scsj.supermarket.adapter.CouponAdapter;
import com.scsj.supermarket.adapter.LeftMenuAdapter;
import com.scsj.supermarket.adapter.RightDishAdapter;
import com.scsj.supermarket.base.MarketBase;
import com.scsj.supermarket.bean.BaseBean;
import com.scsj.supermarket.bean.MarketCouPounBean;
import com.scsj.supermarket.bean.MarketDetailBean;
import com.scsj.supermarket.bean.MarketRightBean;
import com.scsj.supermarket.bean.MarketShopCarBean;
import com.scsj.supermarket.bean.ModelDishBean;
import com.scsj.supermarket.bean.ModelDishMenuBean;
import com.scsj.supermarket.bean.ModelShopCartBean;
import com.scsj.supermarket.customview.RxDialogShopCart;
import com.scsj.supermarket.customview.RxFakeAddImageView;
import com.scsj.supermarket.customview.RxPointFTypeEvaluator;
import com.scsj.supermarket.interfaces.ShopCartInterface;
import com.scsj.supermarket.presenter.MarketPresenter;
import com.scsj.supermarket.utils.SkipUtils;
import com.scsj.supermarket.view.fragment.basemodel.BaseFragment;

import java.util.ArrayList;

import es.dmoral.toasty.Toasty;
import okhttp3.RequestBody;

/**
 * 商家店铺页面
 */

public class MarketFragment extends BaseFragment implements LeftMenuAdapter.onItemSelectedListener, ShopCartInterface, RxDialogShopCart.ShopCartDialogImp, MarketBase.IView {

    private TextView totalPriceTextView;
    private TextView totalPriceNumTextView;
    private RelativeLayout mMainLayout;
    public static final String TAG = "商家店铺";
    private LinearLayout headerLayout;
    private TextView headerView;
    private RecyclerView mLeftMenu;
    private RecyclerView mRightMenu;
    private ArrayList<ModelDishMenuBean> mModelDishMenuList;//数据源
    private ModelShopCartBean mModelShopCartBean;
    private ModelDishMenuBean headMenu;
    private LeftMenuAdapter leftAdapter;
    private RightDishAdapter rightAdapter;
    private boolean leftClickType = false;//左侧菜单点击引发的右侧联动
    private ImageView mShoppingCart;
    private RelativeLayout mShoppingCartBottom;
    private FrameLayout mShoppingCartLayout;
    private TextView go_pay_tv;
    private MarketPresenter presenter;
    private ArrayList<String> leftTitle;
    private ArrayList<ModelDishBean> discountList;
    private ArrayList<ModelDishBean> elseList;
    private ArrayList<ModelDishBean> seckillList;
    private CouponAdapter couponAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_market, null);

        leftTitle = new ArrayList<>();

//        presenter = new MarketPresenter(this);
//
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("shopStoreId", "3cad7a54-79d4-11e8-afb7-70106fb15682");
//        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=utf-8"), jsonObject.toString());
//        presenter.deliverMarketShopCarList(body);

//        JSONObject jsonObject1 = new JSONObject();
//        jsonObject1.put("id", "3cad7a54-79d4-11e8-afb7-70106fb15682");
//        jsonObject1.put("userId", "1");
//        RequestBody body1 = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=utf-8"), jsonObject1.toString());
//        presenter.deliverMarketDetailList(body1);

//        JSONObject jsonObject2 = new JSONObject();
//        jsonObject2.put("fatherBySonId", "202");
//        jsonObject2.put("id", "2");
//        RequestBody body2 = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=utf-8"), jsonObject2.toString());
//        presenter.deliverMarketRightList(body2);

//        JSONObject jsonObject3 = new JSONObject();
//        jsonObject3.put("shopStoreId","1");
//        jsonObject3.put("goodsId","g3");
//        jsonObject3.put("state","1");
//        RequestBody body3 = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=utf-8"), jsonObject3.toString());
//        presenter.deliverControlMarketShopcarList(body3);

        initData();

        initView(view, null);
        initListener();
        initAdapter();
        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        leftAdapter.removeItemSelectedListener(this);
    }


    protected void initView(View view, Bundle savedInstanceState) {
        headerLayout = view.findViewById(R.id.right_menu_ll);
        headerView = view.findViewById(R.id.right_menu_tv);
        mRightMenu = view.findViewById(R.id.right_menu);
        mLeftMenu = view.findViewById(R.id.left_menu);
        mLeftMenu.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRightMenu.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        mMainLayout = view.findViewById(R.id.main_layout);
        mShoppingCartBottom = view.findViewById(R.id.shopping_cart_bottom);
        totalPriceNumTextView = view.findViewById(R.id.shopping_cart_total_num);
        mShoppingCart = view.findViewById(R.id.shopping_cart);
        totalPriceTextView = view.findViewById(R.id.shopping_cart_total_tv);
        mShoppingCartLayout = view.findViewById(R.id.shopping_cart_layout);
        go_pay_tv = view.findViewById(R.id.go_pay_tv);

    }


    protected void initListener() {

        mRightMenu.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (recyclerView.canScrollVertically(1) == false) {//无法下滑
                    showHeadView();
                    return;
                }
                View underView = null;
                if (dy > 0)
                    underView = mRightMenu.findChildViewUnder(headerLayout.getX(), headerLayout.getMeasuredHeight() + 1);
                else
                    underView = mRightMenu.findChildViewUnder(headerLayout.getX(), 0);
                if (underView != null && underView.getContentDescription() != null) {
                    int position = Integer.parseInt(underView.getContentDescription().toString());
                    ModelDishMenuBean menu = rightAdapter.getMenuOfMenuByPosition(position);

                    if (leftClickType || !menu.getMenuName().equals(headMenu.getMenuName())) {
                        if (dy > 0 && headerLayout.getTranslationY() <= 1 && headerLayout.getTranslationY() >= -1 * headerLayout.getMeasuredHeight() * 4 / 5 && !leftClickType) {// underView.getTop()>9
                            int dealtY = underView.getTop() - headerLayout.getMeasuredHeight();
                            headerLayout.setTranslationY(dealtY);
//                            Log.e(TAG, "onScrolled: "+headerLayout.getTranslationY()+"   "+headerLayout.getBottom()+"  -  "+headerLayout.getMeasuredHeight() );
                        } else if (dy < 0 && headerLayout.getTranslationY() <= 0 && !leftClickType) {
                            headerView.setText(menu.getMenuName());
                            int dealtY = underView.getBottom() - headerLayout.getMeasuredHeight();
                            headerLayout.setTranslationY(dealtY);
//                            Log.e(TAG, "onScrolled: "+headerLayout.getTranslationY()+"   "+headerLayout.getBottom()+"  -  "+headerLayout.getMeasuredHeight() );
                        } else {
                            headerLayout.setTranslationY(0);
                            headMenu = menu;
                            headerView.setText(headMenu.getMenuName());
                            for (int i = 0; i < mModelDishMenuList.size(); i++) {
                                if (mModelDishMenuList.get(i) == headMenu) {
                                    leftAdapter.setSelectedNum(i);
                                    break;
                                }
                            }
                            if (leftClickType) leftClickType = false;
                            Log.e(TAG, "onScrolled: " + menu.getMenuName());
                        }
                    }
                }
            }
        });
        mShoppingCartLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showCart();
            }
        });
    }

    private void initAdapter() {
        leftAdapter = new LeftMenuAdapter(getActivity(), mModelDishMenuList, presenter);
        rightAdapter = new RightDishAdapter(getActivity(), mModelDishMenuList, mModelShopCartBean);
        mRightMenu.setAdapter(rightAdapter);
        mLeftMenu.setAdapter(leftAdapter);
        leftAdapter.addItemSelectedListener(this);
        rightAdapter.setShopCartInterface(this);
        initHeadView();
    }

    private void initHeadView() {
        headMenu = rightAdapter.getMenuOfMenuByPosition(0);
        headerLayout.setContentDescription("0");
        headerView.setText(headMenu.getMenuName());
    }


    protected void initData() {
        mModelShopCartBean = new ModelShopCartBean();
        mModelDishMenuList = new ArrayList<>();

        ArrayList<ModelDishBean> dishs1 = new ArrayList<>();
        dishs1.add(new ModelDishBean("面包", 1.0, 10));
        dishs1.add(new ModelDishBean("蛋挞", 1.0, 10));
        dishs1.add(new ModelDishBean("牛奶", 1.0, 10));
        dishs1.add(new ModelDishBean("肠粉", 1.0, 10));
        dishs1.add(new ModelDishBean("绿茶饼", 1.0, 10));
        dishs1.add(new ModelDishBean("花卷", 1.0, 10));
        dishs1.add(new ModelDishBean("包子", 1.0, 10));
        ModelDishMenuBean breakfast = new ModelDishMenuBean("早点", dishs1);

        ArrayList<ModelDishBean> dishs2 = new ArrayList<>();
        dishs2.add(new ModelDishBean("粥", 1.0, 10));
        dishs2.add(new ModelDishBean("炒饭", 1.0, 10));
        dishs2.add(new ModelDishBean("炒米粉", 1.0, 10));
        dishs2.add(new ModelDishBean("炒粿条", 1.0, 10));
        dishs2.add(new ModelDishBean("炒牛河", 1.0, 10));
        dishs2.add(new ModelDishBean("炒菜", 1.0, 10));
        ModelDishMenuBean launch = new ModelDishMenuBean("午餐", dishs2);

        ArrayList<ModelDishBean> dishs3 = new ArrayList<>();
        dishs3.add(new ModelDishBean("淋菜", 1.0, 10));
        dishs3.add(new ModelDishBean("川菜", 1.0, 10));
        dishs3.add(new ModelDishBean("湘菜", 1.0, 10));
        dishs3.add(new ModelDishBean("粤菜", 1.0, 10));
        dishs3.add(new ModelDishBean("赣菜", 1.0, 10));
        dishs3.add(new ModelDishBean("东北菜", 1.0, 10));
        ModelDishMenuBean evening = new ModelDishMenuBean("晚餐", dishs3);

        ArrayList<ModelDishBean> dishs4 = new ArrayList<>();
        dishs4.add(new ModelDishBean("淋菜", 1.0, 10));
        dishs4.add(new ModelDishBean("川菜", 1.0, 10));
        dishs4.add(new ModelDishBean("湘菜", 1.0, 10));
        dishs4.add(new ModelDishBean("湘菜", 1.0, 10));
        dishs4.add(new ModelDishBean("湘菜1", 1.0, 10));
        dishs4.add(new ModelDishBean("湘菜2", 1.0, 10));
        dishs4.add(new ModelDishBean("湘菜3", 1.0, 10));
        dishs4.add(new ModelDishBean("湘菜4", 1.0, 10));
        dishs4.add(new ModelDishBean("湘菜5", 1.0, 10));
        dishs4.add(new ModelDishBean("湘菜6", 1.0, 10));
        dishs4.add(new ModelDishBean("湘菜7", 1.0, 10));
        dishs4.add(new ModelDishBean("湘菜8", 1.0, 10));
        dishs4.add(new ModelDishBean("粤菜", 1.0, 10));
        dishs4.add(new ModelDishBean("赣菜", 1.0, 10));
        dishs4.add(new ModelDishBean("东北菜", 1.0, 10));
        ModelDishMenuBean menu1 = new ModelDishMenuBean("夜宵、小菜、凉拌菜", dishs4);

        mModelDishMenuList.add(breakfast);
        mModelDishMenuList.add(launch);
        mModelDishMenuList.add(evening);
        mModelDishMenuList.add(menu1);
    }

    private void showHeadView() {
        headerLayout.setTranslationY(0);
        View underView = mRightMenu.findChildViewUnder(headerView.getX(), 0);
        if (underView != null && underView.getContentDescription() != null) {
            int position = Integer.parseInt(underView.getContentDescription().toString());
            ModelDishMenuBean menu = rightAdapter.getMenuOfMenuByPosition(position + 1);
            headMenu = menu;
            headerView.setText(headMenu.getMenuName());
            for (int i = 0; i < mModelDishMenuList.size(); i++) {
                if (mModelDishMenuList.get(i) == headMenu) {
                    leftAdapter.setSelectedNum(i);
                    break;
                }
            }
        }
    }

    protected int getLayoutId() {
        return 0;
    }

    @Override
    public void add(View view, int postion) {
        int[] addLocation = new int[2];
        int[] cartLocation = new int[2];
        int[] recycleLocation = new int[2];
        view.getLocationInWindow(addLocation);
        mShoppingCart.getLocationInWindow(cartLocation);
        mRightMenu.getLocationInWindow(recycleLocation);

        PointF startP = new PointF();
        PointF endP = new PointF();
        PointF controlP = new PointF();

        startP.x = addLocation[0];
        startP.y = addLocation[1] - recycleLocation[1];
        endP.x = cartLocation[0];
        endP.y = cartLocation[1] - recycleLocation[1];
        controlP.x = endP.x;
        controlP.y = startP.y;

        final RxFakeAddImageView rxFakeAddImageView = new RxFakeAddImageView(getActivity());
        mMainLayout.addView(rxFakeAddImageView);
        rxFakeAddImageView.setImageResource(R.mipmap.cart_add);
        rxFakeAddImageView.getLayoutParams().width = getResources().getDimensionPixelSize(R.dimen.item_dish_circle_size);
        rxFakeAddImageView.getLayoutParams().height = getResources().getDimensionPixelSize(R.dimen.item_dish_circle_size);
        rxFakeAddImageView.setVisibility(View.VISIBLE);
        ObjectAnimator addAnimator = ObjectAnimator.ofObject(rxFakeAddImageView, "mPointF",
                new RxPointFTypeEvaluator(controlP), startP, endP);
        addAnimator.setInterpolator(new AccelerateInterpolator());
        addAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
                rxFakeAddImageView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animator animator) {
                rxFakeAddImageView.setVisibility(View.GONE);
                mMainLayout.removeView(rxFakeAddImageView);
            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });

        ObjectAnimator scaleAnimatorX = new ObjectAnimator().ofFloat(mShoppingCart, "scaleX", 0.6f, 1.0f);
        ObjectAnimator scaleAnimatorY = new ObjectAnimator().ofFloat(mShoppingCart, "scaleY", 0.6f, 1.0f);
        scaleAnimatorX.setInterpolator(new AccelerateInterpolator());
        scaleAnimatorY.setInterpolator(new AccelerateInterpolator());
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.play(scaleAnimatorX).with(scaleAnimatorY).after(addAnimator);
        animatorSet.setDuration(800);
        animatorSet.start();

        showTotalPrice();
    }

    private void showCart() {

        if (mModelShopCartBean != null && mModelShopCartBean.getShoppingAccount() > 0) {

            RxDialogShopCart dialog = new RxDialogShopCart(getActivity(), mModelShopCartBean, R.style.cartdialog);
            Window window = dialog.getWindow();
            dialog.setShopCartDialogImp(this);
            dialog.setCanceledOnTouchOutside(true);
            dialog.setCancelable(true);
            dialog.show();
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = WindowManager.LayoutParams.MATCH_PARENT;
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            params.gravity = Gravity.BOTTOM;
            params.dimAmount = 0.5f;
            window.setAttributes(params);

        }
    }

    @Override
    public void remove(View view, int position) {
        showTotalPrice();
    }


    @Override
    public void onLeftItemSelected(int position, ModelDishMenuBean menu) {
        int sum = 0;
        for (int i = 0; i < position; i++) {
            sum += mModelDishMenuList.get(i).getModelDishList().size() + 1;
        }
        LinearLayoutManager layoutManager = (LinearLayoutManager) mRightMenu.getLayoutManager();
        layoutManager.scrollToPositionWithOffset(sum, 0);
        leftClickType = true;
    }


    @Override
    public void dialogDismiss() {
        showTotalPrice();
        rightAdapter.notifyDataSetChanged();
    }

    private void showTotalPrice() {
        if (mModelShopCartBean != null && mModelShopCartBean.getShoppingTotalPrice() > 0) {
            go_pay_tv.setVisibility(View.VISIBLE);
            totalPriceTextView.setVisibility(View.VISIBLE);
            totalPriceTextView.setText("¥ " + mModelShopCartBean.getShoppingTotalPrice());
            totalPriceNumTextView.setVisibility(View.VISIBLE);
            totalPriceNumTextView.setText("" + mModelShopCartBean.getShoppingAccount());
            go_pay_tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SkipUtils.toOrderPayPage(getActivity());
                }
            });
        } else {
            totalPriceTextView.setVisibility(View.GONE);
            totalPriceNumTextView.setVisibility(View.GONE);
            go_pay_tv.setVisibility(View.GONE);
        }
    }

    @Override
    public void showSuccessMsg(String s) {
        Toasty.success(getActivity(), s).show();
        Logger.e("66666666666666666666666" + s);
    }

    @Override
    public void showErrorMsg(String s) {
        Toasty.error(getActivity(), s).show();
        Logger.e("55555555555555555555555" + s);
    }

    /**
     * 店铺内购物车
     *
     * @param marketShopCarData
     */
    @Override
    public void setMarketShopCarData(MarketShopCarBean marketShopCarData) {

    }

    /**
     * 店铺内购物车数量加减
     *
     * @param baseBean
     */
    @Override
    public void controlMarketShopCarData(BaseBean baseBean) {

    }


    /**
     * 店铺左侧数据
     *
     * @param marketDetailData
     */
    @Override
    public void setMarketDetailData(final MarketDetailBean marketDetailData) {

// TODO: 2018/7/5 秒杀 促销 折扣 判空 处理
/**
 *  促销
 */
//        int promoteSize = marketDetailData.getData().getPromotionName().getPromotionvo().size();
//        ArrayList<ModelDishBean> promoteList = new ArrayList<>();
//        for (int i = 0; i < promoteSize; i++) {
//            MarketDetailBean.DataBean.PromotionNameBean.PromotionvoBean promotionvoBean = marketDetailData.getData().getPromotionName().getPromotionvo().get(i);
//           promoteList.add(new ModelDishBean("", 0,0));
//        }
//        mModelDishMenuList.add(new ModelDishMenuBean(marketDetailData.getData().getPromotionName().getName(),promoteList));
/**
 * 折扣
 */
//        discountList = new ArrayList<>();
//        discountList.add(new ModelDishBean("", 0, 0));
//        mModelDishMenuList.add(new ModelDishMenuBean(marketDetailData.getData().getDiscountName().getName(), discountList));
/**
 * 秒杀
 */
//        seckillList = new ArrayList<>();
//        seckillList.add(new ModelDishBean("",0,0));
//        mModelDishMenuList.add(new ModelDishMenuBean(marketDetailData.getData().getSeckillName().getName(),seckillList));
/**
 * 其余
 */
        int size = marketDetailData.getData().getAppLeftFirstClassifyVo().size();
        for (int i = 0; i < size; i++) {
            elseList = new ArrayList<>();
            leftTitle.add(marketDetailData.getData().getAppLeftFirstClassifyVo().get(i).getGoodsclasslist().getName());
            elseList.add(new ModelDishBean("", 0, 0));
            mModelDishMenuList.add(new ModelDishMenuBean(marketDetailData.getData().getAppLeftFirstClassifyVo().get(i).getGoodsclasslist().getName(), elseList));
        }
        initAdapter();
        leftAdapter.addItemSelectedListener(new LeftMenuAdapter.onItemSelectedListener() {
            @Override
            public void onLeftItemSelected(int postion, ModelDishMenuBean menu) {

                JSONObject jsonObject2 = new JSONObject();
                jsonObject2.put("fatherBySonId", marketDetailData.getData().getAppLeftFirstClassifyVo().get(postion).getId());
                jsonObject2.put("id", marketDetailData.getData().getAppHeadStoreVo().getStores().getId());
                RequestBody body2 = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=utf-8"), jsonObject2.toString());
                presenter.deliverMarketRightList(body2);
           }
        });
    }

    /**
     * 店铺内优惠券
     *
     * @param marketCoupounData
     */
    @Override
    public void setMarketCoupounData(MarketCouPounBean marketCoupounData) {


    }

    /**
     * 店铺右侧数据
     *
     * @param marketRightBean
     */
    @Override
    public void setMarketRightData(MarketRightBean marketRightBean) {
        int size = marketRightBean.getData().getList().size();
        for (int i = 0; i < size; i++) {
            elseList.set(i, new ModelDishBean(marketRightBean.getData().getList().get(i).getGoodsName(), marketRightBean.getData().getList().get(i).getGoodsPrice(), marketRightBean.getData().getList().get(i).getGoodsPromotionPrice()));
            mModelDishMenuList.set(i, new ModelDishMenuBean(leftTitle.get(i), elseList));
        }
        rightAdapter.setData(mModelDishMenuList);
    }
}
